package com.rfsp.common.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.util.Assert;

public class XssUtils {
	
	/**
	 * xss反替换（适用于map类型的）
	 * @param map
	 * @return
	 */
	public static Map<String,Object> replaceUnXss(Map<String,Object> map){
		if(null != map && !map.isEmpty()){
			for(Iterator<String> i = map.keySet().iterator(); i.hasNext(); ) {
				String key = i.next();
				if(map.get(key) != null){
				    String temp = replaceUnXssAll(map.get(key).toString());
				    map.put(key, temp);
				}
			}
		}
		return map;
	}
	
	/**
	 * xss反替换
	 * @param map
	 * @return
	 */
	public static <T> T replaceUnXss(T obj){
		
		if (obj == null) return null;

		for(Field field : obj.getClass().getDeclaredFields()) {
			try {
				if("java.lang.String".equals(field.getType().getName())) {
					field.setAccessible(true);
					String val = (String) field.get(obj);
					val = XssUtils.replaceUnXssAll(val);
					field.set(obj, val);
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
				
			}
		}
		return obj;
	}
	

	/**
	 * xss替换特殊字符
	 * @param map
	 * @return
	 */
	public static <T> T replaceXss(T obj){
		
		if (obj == null) return null;

		for(Field field : obj.getClass().getDeclaredFields()) {
			try {
				if("java.lang.String".equals(field.getType().getName())) {
					field.setAccessible(true);
					String val = (String) field.get(obj);
					val = XssUtils.replaceXssAll(val);
					field.set(obj, val);
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
				
			}
		}
		return obj;
	}
	
	/**
	 * xss替换（适用于map类型的）
	 * @param map
	 * @return
	 */
	public static Map<String,Object> replaceXss(Map<String,Object> map){
		if(null != map && !map.isEmpty()){
			for(Iterator<String> i = map.keySet().iterator(); i.hasNext(); ) {
				String key = i.next();
				if(map.get(key) != null){
				    String temp = replaceXssAll(map.get(key).toString());
				    map.put(key, temp);
				}
			}
		}
		return map;
	}

	/**
	 * 为正替换使用
	 * @param source the source bean
	 * @param target the target bean
	 * @param editable the class (or interface) to restrict property setting to
	 * @param ignoreProperties array of property names to ignore
	 * @throws BeansException if the copying failed
	 * @see BeanWrapper
	 */
	private static void copyUnProperties(Object source, Object target, Class<?> editable, String[] ignoreProperties)
			throws BeansException {

		Assert.notNull(source, "Source must not be null");
		Assert.notNull(target, "Target must not be null");

		Class<?> actualEditable = target.getClass();
		if (editable != null) {
			if (!editable.isInstance(target)) {
				throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
						"] not assignable to Editable class [" + editable.getName() + "]");
			}
			actualEditable = editable;
		}
		PropertyDescriptor[] targetPds =org.springframework.beans.BeanUtils.getPropertyDescriptors(actualEditable);
		List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

		for (PropertyDescriptor targetPd : targetPds) {
			if (targetPd.getWriteMethod() != null &&
					(ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
				PropertyDescriptor sourcePd = org.springframework.beans.BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null && sourcePd.getReadMethod() != null) {
					try {
						Method readMethod = sourcePd.getReadMethod();
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						//判断value是否为字符，如果是 则替换
						if(value instanceof String){
							value  = XssUtils.replaceXssAll((String)value);
						}
						Method writeMethod = targetPd.getWriteMethod();
						if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
							writeMethod.setAccessible(true);
						}
						writeMethod.invoke(target, value);
					}
					catch (Exception ex) {
						//throw new FatalBeanException("Could not copy properties from source to target", ex);
					}
				}
			}
		}
	}

	/**
	 * xss正替换
	 * @param source the source bean
	 * @param target the target bean
	 * @throws BeansException if the copying failed
	 * @see BeanWrapper
	 */
	public static void copyUnProperties(Object source, Object target) throws BeansException {
		copyUnProperties(source, target, null, null);
	}
	
	/**
	 * xss反替换
	 * @param xss
	 * @return
	 */
	public   static String  replaceUnXssAll(String unxss){
		if(StringUtils.isEmpty(unxss)) {
			return unxss;
		}
		unxss = unxss.replaceAll("&amp;", "&");//&amp; 符号
        unxss = unxss.replaceAll("&lt;", "<").replaceAll("&gt;", ">");//<>（尖括号）
        unxss = unxss.replaceAll("&#40;", "\\(").replaceAll("&#41;", "\\)");//()（括号）
        unxss = unxss.replaceAll("&#39;", "'");//\\'（反斜杠转义单引号）
        unxss = unxss.replaceAll("&brvbar;" , "\\|" );//| &#166; &brvbar;
        unxss = unxss.replaceAll("&#59;" ,"\\;");//; &#59;
        unxss = unxss.replaceAll("&#36;" ,"\\$");//$ &#36;
        unxss = unxss.replaceAll("&#37;" ,"\\%");//% &#37;
        unxss = unxss.replaceAll("&#64;" ,"\\@");//@（at 符号） @ &#64; 
        unxss = unxss.replaceAll("&#43;" ,"\\+");//+ &#43
        unxss = unxss.replaceAll("&#44;" ,",");
        unxss = unxss.replaceAll("&#92;" ,"\\\\");//\ &#92;
        unxss = unxss.replaceAll("&#13;" ,"\r");//\r 回车
        unxss = unxss.replaceAll("&#10;" ,"\n");//\n 换行
        unxss = unxss.replaceAll("&#34;" ,"\"");
		return unxss;
	}
	
	/**
	 * xss替换
	 * @param xss
	 * @return
	 */
	public   static String  replaceXssAll(String xss){
		if(StringUtils.isEmpty(xss)) {
			return xss;
		}
		xss = xss.replaceAll("&", "&amp;");//& 符号
        xss = xss.replaceAll("<", "&lt;").replaceAll(">", "&gt;");//<>（尖括号）
        xss = xss.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");//()（括号）
        xss = xss.replaceAll("'", "&#39;");//\\'（反斜杠转义单引号）
        xss = xss.replaceAll("eval\\((.*)\\)", "");
        //xss = xss.replaceAll("\\|", "&brvbar;");//| &#166; &brvbar;
        xss = xss.replaceAll("\\$", "&#36;");//$ &#36;
        xss = xss.replaceAll("\\%", "&#37;");//% &#37;
        xss = xss.replaceAll("\\@", "&#64;");//@（at 符号） @ &#64; 
        xss = xss.replaceAll("\\+", "&#43;");//+ &#43
        xss = xss.replaceAll("\\\\", "&#92;");//\ &#92;
        xss = xss.replaceAll("\"", "&#34;");
        xss = xss.trim();
		return xss;
	}
	
	/**
	 * xss替换
	 * @param xss
	 * @return
	 */
	public   static String  replaceChineseLength(String values){
		if(StringUtils.isEmpty(values)) {
			return values;
		}
		String temp = new String(values);
		
		temp = temp.replaceAll("[^\\x00-\\xff]", "**");  
        
		return temp;
	}
	
	/**
	 * Note: override  {@link org.springframework.beans.BeanUtils#copyProperties(Object, Object, String[])}
	 * 
	 * 还原Bean,修复字符替换
	 * 
	 * Copy the property values of the given source bean into the given target bean.
	 * <p>Note: The source and target classes do not have to match or even be derived
	 * from each other, as long as the properties match. Any bean properties that the
	 * source bean exposes but the target bean does not will silently be ignored.
	 * @param source the source bean
	 * @param target the target bean
	 * @param editable the class (or interface) to restrict property setting to
	 * @param ignoreProperties array of property names to ignore
	 * @throws BeansException if the copying failed
	 * @see BeanWrapper
	 */
	private static void copyProperties(Object source, Object target, Class<?> editable, String[] ignoreProperties)
			throws BeansException {

		Assert.notNull(source, "Source must not be null");
		Assert.notNull(target, "Target must not be null");

		Class<?> actualEditable = target.getClass();
		if (editable != null) {
			if (!editable.isInstance(target)) {
				throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
						"] not assignable to Editable class [" + editable.getName() + "]");
			}
			actualEditable = editable;
		}
		PropertyDescriptor[] targetPds =org.springframework.beans.BeanUtils.getPropertyDescriptors(actualEditable);
		List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

		for (PropertyDescriptor targetPd : targetPds) {
			if (targetPd.getWriteMethod() != null &&
					(ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
				PropertyDescriptor sourcePd = org.springframework.beans.BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null && sourcePd.getReadMethod() != null) {
					try {
						Method readMethod = sourcePd.getReadMethod();
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						//判断value是否为字符，如果是 则替换
						if(value instanceof String){
							value  = XssUtils.replaceUnXssAll((String)value);
						}
						Method writeMethod = targetPd.getWriteMethod();
						if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
							writeMethod.setAccessible(true);
						}
						writeMethod.invoke(target, value);
					}
					catch (Throwable ex) {
						//throw new FatalBeanException("Could not copy properties from source to target", ex);
					}
				}
			}
		}
	}
	
	/**
	 * 还原Bean,修复字符替换
	 * Copy the property values of the given source bean into the target bean.
	 * <p>Note: The source and target classes do not have to match or even be derived
	 * from each other, as long as the properties match. Any bean properties that the
	 * source bean exposes but the target bean does not will silently be ignored.
	 * <p>This is just a convenience method. For more complex transfer needs,
	 * consider using a full BeanWrapper.
	 * @param source the source bean
	 * @param target the target bean
	 * @throws BeansException if the copying failed
	 * @see BeanWrapper
	 */
	public static void copyProperties(Object source, Object target) throws BeansException {
		copyProperties(source, target, null, null);
	}
	
}
